import React, { useEffect } from 'react';
import { Spin, Space, DatePicker, Button } from 'antd';
import moment from 'moment';
import _ from 'lodash';

import { TRDefault } from '@/components';
import { useTRState, TjSelect, TjSegmented, TjChart, TjTable } from '@/pages/ETrade/components';

import { tableHead, fmtData } from './helper';
import { getProvinceSpotOptions, queryProvinceSpotData } from '../services';
import styles from './index.less';
import { useThemeChange } from '@/hooks';

export default () => {
  /** data */
  const allValue = '-1';
  const initForm = () => {
    return {
      date: moment().add(-1, 'day'),
      tradeRole: '2', // 交易角色：1-购方 2-售方
      marketName: null,
      marketNameList: [],
      dataType: 1, // 0全部 1日前 2实时
    };
  };
  const [state, setState] = useTRState({
    ...initForm(),
    loading: true,
    optionsMap: {},
    options: [],
    options2: [],
    // result
    result: null, // 原始数据
    chartOption: null,
    tableData: [],
  });
  const { theme } = useThemeChange();

  /** life */
  useEffect(() => {
    init();
  }, [state.date]);

  useEffect(() => {
    setTimeout(() => {
      const { chartOption } = fmtData(state.result, state.dataType);
      setState({ chartOption });
    }, 1);
  }, [theme]);

  const fetch = async (params) => {
    setState({ loading: true });
    const res = await queryProvinceSpotData(params);
    // let result = res?.data?.map || {};
    let result = res?.data?.clearMap || {};
    if (!Object.keys(result).length) {
      result = null;
    }
    setState({
      result,
      loading: false,
      ...fmtData(result, state.dataType),
    });
  };

  /** method */
  const init = async () => {
    // 接口参数设计bug，现状不应该再携带参数了，没意义
    const res = await getProvinceSpotOptions({
      tradeRole: '2',
      date: moment(state.date).format('YYYY-MM-DD'),
    });
    const buyerList = res?.data?.buyerMarketNameList || [];
    const sellerList = res?.data?.sellerMarketNameList || [];
    const buyerOptions = [...buyerList.map((t) => ({ label: t, value: t }))];
    const sellerOptions = [...sellerList.map((t) => ({ label: t, value: t }))];
    state.optionsMap = {
      1: {
        options: [...buyerOptions],
        options2: [{ label: '购方汇总', value: allValue }, ...buyerOptions],
      },
      2: {
        options: [...sellerOptions],
        options2: [{ label: '售方汇总', value: allValue }, ...sellerOptions],
      },
    };
    setState({
      optionsMap: state.optionsMap,
    });
    changeTradeRole('2');
    _onFinish();
  };

  const _onFinish = () => {
    const params = {
      data: state.date.format('YYYY-MM-DD'),
      tradeRole: state.tradeRole,
      type: '',
    };
    if (state.marketName === allValue) {
      params.marketNameList = state.marketNameList;
      params.marketName = '';
    } else {
      params.marketName = state.marketName;
    }
    switch (state.dataType) {
      case 0:
        params.type = '';
        break;
      case 1:
        params.type = 'dayahead';
        break;
      case 2:
        params.type = 'realTime';
        break;
    }
    fetch(params);
  };

  const _onReset = () => {
    setState({
      ...initForm(),
    });
    changeTradeRole('2');
  };

  const changeTradeRole = (v) => {
    // 默认全选
    const { options, options2 } = state.optionsMap[v];
    state.tradeRole = v;
    state.options = [...options];
    state.options2 = [...options2];
    setState({
      tradeRole: state.tradeRole,
      options: state.options,
      options2: state.options2,
    });
    changeMarket(allValue);
  };

  const changeMarket = (v) => {
    state.marketName = v;
    state.marketNameList = v === allValue ? state.options.map((x) => x.value) : [];
    setState({
      marketName: state.marketName,
      marketNameList: state.marketNameList,
    });
  };

  const changeDataType = (dataType) => {
    setState({
      dataType,
      ...fmtData(state.result, dataType),
    });
  };

  /** render */
  const _renderMain = () => {
    if (state.loading) return null;
    if (!state.result) return <TRDefault type="emptysm" />;
    return (
      <>
        <div className={styles.chart}>
          <TjChart option={state.chartOption} />
        </div>
        <div className={styles.table}>
          <TjTable
            primaryKey="point"
            columns={tableHead}
            dataSource={state.tableData}
            style={{ height: '100%' }}
          />
        </div>
      </>
    );
  };
  return (
    <Spin spinning={state.loading} wrapperClassName={styles.content}>
      <div className={styles.head}>
        <Space size={16} wrap>
          <DatePicker
            value={state.date}
            allowClear={false}
            format={'YYYYMMDD'}
            disabledDate={(v) => v > moment()}
            onChange={(date) => setState({ date })}
          />
          <TjSegmented
            value={state.tradeRole}
            onChange={changeTradeRole}
            options={[
              { label: '购方', value: '1' },
              { label: '售方', value: '2' },
            ]}
          />
          <TjSelect
            value={state.marketName}
            options={state.options2}
            onChange={changeMarket}
            showSearch={true}
          />
          {state.marketName === allValue && (
            <TjSelect
              value={state.marketNameList}
              options={state.options}
              onChange={(marketNameList) => setState({ marketNameList })}
              mode="multiple"
            />
          )}
          <TjSegmented
            value={state.dataType}
            options={[
              { label: '全部', value: 0 },
              { label: '日前', value: 1 },
              { label: '实时', value: 2 },
            ]}
            onChange={changeDataType}
          />
          <Space size={16}>
            <Button style={{ width: 98, height: 32 }} type="primary" onClick={_onFinish}>
              查询
            </Button>
            <Button style={{ width: 98, height: 32 }} ghost onClick={_onReset}>
              重置
            </Button>
          </Space>
        </Space>
      </div>
      <div className={styles.main}>{_renderMain()}</div>
    </Spin>
  );
};
